package com.statapp;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;

/** 
 * This class represents a pie chart to visualize product share data.
 * 
 * @author Peter Goldenbogen (Munich University of Applied Science)
 * @version 1.0 
 */

public class ProductShare{
	
	private final String url = "http://"+ StatAppActivity.server_address + "/ChartService/rest/kpi/get_product_share";
	private String title = "Chart Title";
	private String identifier = "id";
	private final int values[] = {0,0,0};
	private final String categories[] = {"","",""};
	private int colors[] = {Color.BLUE, Color.GREEN, Color.YELLOW};
	
	/**
	 * Sets up PieChartIntent with rendering parameters and data sets to display product share data
	 * @param context The application context
	 * @return An Intent which will start an activity to display a pie chart visualizing the XML data
	 * @see PieChartIntent
	 */
	public Intent getIntent(Context context) {

		String xmlData = this.getProductShareData();
		
		if(xmlData != null){
			this.parseXml(xmlData);		
		}
		else{
			Toast.makeText(context, "No data available!", Toast.LENGTH_SHORT).show();
			return new Intent(context, StatAppActivity.class);
		}
		
		CategorySeries cs = new CategorySeries(title);
		
		for(int value = 0; value < values.length ;value++){
			cs.add(categories[value], values[value]);
		}
		
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setChartTitle(title);
		renderer.setChartTitleTextSize(25);
		renderer.setZoomButtonsVisible(true);
		renderer.setLabelsTextSize(20);
		
		for(int color : colors){
			SimpleSeriesRenderer simpleSR = new SimpleSeriesRenderer();
			simpleSR.setColor(color);
			renderer.addSeriesRenderer(simpleSR);
		}
		
		Intent intent = ChartFactory.getPieChartIntent(context, cs, renderer, "Product Share");
		return intent;
	}
	
	/**
	 * Fetches Data from a XML based REST WS (GET)
	 * @param context The application context
	 * @return a String holding all XML data returned by the server
	 */
	public String getProductShareData(){
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String result = null;
		
		try {
			result = httpClient.execute(request, handler);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		httpClient.getConnectionManager().shutdown();
		Log.v("statapp", "get_product_share called! Result:" + result);
		
		return result;
	}
	
	/**
	 * Parses the XML data an updates class variables
	 * @param the String that will be searched for XML data to feed the pie chart
	 */
	public void parseXml(String xml){
		
		Document dom = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			dom = db.parse(is);
			Element root = dom.getDocumentElement();
			NodeList rootNl = root.getChildNodes();
			//keyIndicator
			for(int i = 0; i < rootNl.getLength(); i++){
				
				Node rootNode = rootNl.item(i);
				
				if(rootNode.getNodeName().equalsIgnoreCase("title"))
					title = rootNode.getChildNodes().item(0).getNodeValue();
				
				else if (rootNode.getNodeName().equalsIgnoreCase("identifier"))
					identifier = rootNode.getChildNodes().item(0).getNodeValue();
				
				else if (rootNode.getNodeName().equalsIgnoreCase("pieChart")){
					
					NodeList pieChartNl = rootNode.getChildNodes();
					
					//pieCHart
					for(int j = 0; j < pieChartNl.getLength(); j++){
						
						Node pieNode = pieChartNl.item(j);
						
						NodeList pieValueNl = pieNode.getChildNodes();
						
						//pieValueSeries
						for(int k = 0; k < pieValueNl.getLength(); k++){
						
							Node pieValueNode = pieValueNl.item(k);
							
							if(pieValueNode.getNodeName().equalsIgnoreCase("title"))
								categories[j] = pieValueNode.getChildNodes().item(0).getNodeValue();
							
							if(pieValueNode.getNodeName().equalsIgnoreCase("value"))
								values[j] = Integer.parseInt(pieValueNode.getChildNodes().item(0).getNodeValue());
						}
					}

				}
			}
			
		} catch (ParserConfigurationException e) {
			Log.e("statapp", e.getMessage());
		} catch (SAXException e) {
			Log.e("statapp", e.getMessage());
		} catch (IOException e) {
			Log.e("statapp", e.getMessage());
		}
	}
}
